import gtk
import gobject

from lib.w.widget.base import Base

class ComboBox(Base):

	def __init__(self, w):
		self.w = w
		self.__configure()
		self.idx = []

	def set_value(self, value=None):

		if not value: return

		try:
			self.w.set_active(self.idx.index(value))
		except:
			pass

	def __configure(self):

		ls = gtk.ListStore(gobject.TYPE_STRING)
		self.w.set_model(ls)
		render = gtk.CellRendererText()
		self.w.pack_start(render, True)
		self.w.add_attribute(render, 'text', 0)

	def set_items(self, l):

		self.clear()

		if not type(l) is list: return
		
		for v in l:
			self.append_tuple(v)
		
	def append_tuple(self, v):

		if not type(v) is tuple: return

		self.idx.append(v[0])
		self.w.append_text(self.encode(v[1]))

	def get_value(self):

		act = self.w.get_active()
		if act < 0: return None

		return self.idx[act]

	def clear(self):

		cont = 0
		for i in self.idx:
			self.w.remove_text(cont)
			cont+= 1

		self.idx = []

	def __getattr__(self, attr):
		return getattr(self.w, attr)
